package com.ztjc.day04_internettext;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.ztjc.day04_internettext.util.StreamUtil;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 网络源码查看器
 */
public class MainActivity extends Activity {

    private EditText etPath;
    private TextView tvSrc;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressDialog = new ProgressDialog(this);
    }

    /**
     * 查看网页源码
     * @param view
     */
    public void show(View view) {
        progressDialog.show();
        etPath = (EditText) findViewById(R.id.et_path);
        tvSrc = (TextView) findViewById(R.id.tv_src);
        new DownloadTask().execute(etPath.getText().toString());
    }

    /**
     * 下载网页的异步任务
     */
    class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                if (connection.getResponseCode() == 200) {
                    return StreamUtil.decodeToString(connection.getInputStream());
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            tvSrc.setText(s);
            progressDialog.dismiss();
        }
    }
}
